package com.example.administrator.nurse.present;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.administrator.nurse.R;
import com.example.administrator.nurse.base.BaseActivity;
import com.example.administrator.nurse.common;
import com.example.administrator.nurse.util.InternetHelper;
import com.example.administrator.nurse.util.imageLoderHelper;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.File;

/**
 * Created by Administrator on 2016/4/3.
 *
 */

public class ConfigActivity extends BaseActivity {

    protected ImageLoader imageLoder = ImageLoader.getInstance();
    private ImageView head;
    private Handler hanlder;

    @Override
    protected int setLayotId() {
        return R.layout.config_layout;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        configCommonHeader(ConfigActivity.this, getString(R.string.main_title), 0);
        initHandler();
        /** 退出登录 */
        f(R.id.loginOut).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                common.putStr("isLogin", "no");
                common.putStr("nId", "-1");
                common.putStr("nName", "-1");
                common.putStr("nAccount", "-1");
                common.putStr("nPw", "-1");
                common.putStr("nHeadUrl", "-1");
                common.nHeadUrl="";
                common.isLogin = false;
                startOtherActivity(ConfigActivity.this, LoginActivity.class);
            }
        });
        ((TextView)f(R.id.name)).setText(common.nName);
        ((TextView)f(R.id.id))  .setText("工号" + common.nId);
        head = (ImageView)f(R.id.head);
        imageLoder.displayImage(common.nHeadUrl, head, imageLoderHelper.getLoderOption(R.mipmap.user, 170));
        head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showChosePicDialog();
            }
        });
        /** 修改密码 */
        f(R.id.change_pw).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startOtherActivity(ConfigActivity.this,ForgetPassActivity.class);
//                startLoadingDialog();
//                RequestParams requestParams = new RequestParams();
//                requestParams.put("",);
//                requestParams.put("",);
//                requestParams.put("",);
//                doPost(ChangePw, common.Host + "/Controller/funcController.php?func=forgetPwd",requestParams);
            }
        });
    }

    @Override
    protected void onFailure(int requestCode, Object object, String errorMsg) {
        Log.d("zzzzz",errorMsg);
    }

    @Override
    protected void onSuccess(int requestCode, Object object, String response) {
        switch (requestCode){
            case ChangePw:

                break;
        }
    }

    private final int ChangePw = 0x22;
    private final int UpLoadPic = 0x23;
    private void initHandler(){
        hanlder = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what){
                    case UpLoadPic:
                        stopLoadingDialog();
                        String json = ((String)msg.obj).trim();
                        Log.d("zzzzz","upload file json is "+json);
                        if(json!=null){
                            if(json.equals("0")){
                                t("头像上传失败!");
                            }else if(json.equals("2")){
                                t("头像上传失败!");
                            }else{
                                String[] temp = json.split("_");
                                if(temp[0].equals("1")){
                                    t("头像上传成功!");
                                    common.nHeadUrl = common.Host+"/"+temp[1];
                                    common.getSp(null).edit().putString("nHeadUrl", common.nHeadUrl).commit();
                                    head.setImageBitmap(imageLoderHelper.getRoundedCornerBitmap(headBit));
                                }
                                t("头像上传失败!");
                            }
                        }
                        break;
                }
            }
        };
    }

    private String imageUrl = common.diskCachePath+"_head.jpg";
    private boolean isCamera = false;
    private static final int From_Camera = 0x111;
    private static final int From_Phone  = 0x112;
    private Uri imageUri;
    private void showChosePicDialog(){
        final CharSequence[] items = {"从相册选取", "手机拍照","取消"};
        AlertDialog dlg = new AlertDialog.Builder(ConfigActivity.this).setTitle("选择头像").setItems(items,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int item) {
                        imageUri = Uri.fromFile(new File(imageUrl));
                        if (item == 1) {
                            isCamera = true;
                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//action is capture
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                            startActivityForResult(intent, From_Camera);
                        }
                        if (item == 0) {
                            Intent intent = new Intent();
                            intent.setAction(Intent.ACTION_GET_CONTENT);
                            intent.setType("image/*");
                            intent.putExtra("return-data", true);
                            intent.putExtra("noFaceDetection", true); // no face detection
                            startActivityForResult(intent, From_Phone);
                        }
                        if (item == 2) {
                            dialog.cancel();
                        }
                    }
                }).create();
        dlg.show();
    }

    private Bitmap headBit = null;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case From_Phone:
                Log.d("zzzzz", "pick picture from phone");
                if(data != null){
                    Uri uriTemp = data.getData();
                    if(uriTemp!=null){
                        cropImageUri(uriTemp,100,100,3);
                    }else{
                        try {
                            Bundle extras = data.getExtras();
                            Uri uri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(),(Bitmap)extras.getParcelable("data"), null,null));
                            cropImageUri(uri,100,100,3);
                        } catch (Exception e) {
                            Log.d("zzzzz","uri is null "+e.toString());
                        }
                    }
                }else{
                    Log.d("zzzzz", "date is null from phone" );
                }
                break;
            case From_Camera:
                if(isCamera) {
                    cropImageUri(imageUri, 100, 100, 3);
                }
                break;
            case 3:
                if(data != null) {
                    Uri uriTemp = data.getData();
                    if (uriTemp != null) {
                        Bitmap image;
                        try {
                            //这个方法是根据Uri获取Bitmap图片的静态方法
                            image = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uriTemp);
                            UpLoadPic(image);
                        } catch (Exception e) {
                            Log.d("zzzzz", "case 3: " +e.toString());
                        }
                    } else {
                        Bundle extras = data.getExtras();
                        if (extras != null) {
                            //这里是有些拍照后的图片是直接存放到Bundle中的所以我们可以从这里面获取Bitmap图片
                            Bitmap image = extras.getParcelable("data");
                            UpLoadPic(image);
                        }
                    }
                }
                break;
            default:
                break;
        }
    }

    private void UpLoadPic(Bitmap image){
        if (image != null) {
            /** 开始上传 */
            headBit = image;
            startLoadingDialog();
            if(InternetHelper.checkConnection()){
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String json = InternetHelper.uploadPic
                                    (
                                            common.Host+"/Controller/funcController.php?func=fileUpload"
                                                    +"&id="+common.nId
                                                    +"&type=1"
                                                    +"&idOfHospital="+common.nIdOfHospital,
                                            "head.jpg",
                                            headBit
                                    );
                            Message msg = new Message();
                            msg.what = UpLoadPic;
                            msg.obj  = json;
                            hanlder.sendMessage(msg);
                        }catch (Exception e){

                        }
                    }
                }).start();
            }
        }else{
            Log.d("zzzzz", "case 3: image is null");
        }
    }

    private void cropImageUri(Uri uri, int outputX, int outputY, int requestCode){
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("scale", true);
        //intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        intent.putExtra("return-data", true);
        //intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        startActivityForResult(intent, requestCode);
    }

}
